<template>
    <view class="real-time-info-container">
        <header-vue :back="true" title="发布社区活动" :backUrl="'/views/community/release'" bgColor="transparent"></header-vue>
        <view class="content-box">
            <view class="cover-img" @click="onChooseCover">
                <block v-if="!coverUrl">
                    <view class="cover-placeholder">
                        <u-icon name="plus" color="#bbbbbb" size="48rpx"></u-icon>
                        <text class="cover-tip">添加优质封面</text>
                    </view>
                </block>
                <block v-else>
                    <image class="cover-image" :src="coverUrl" mode="aspectFill" @click.stop="onPreviewCover"></image>
                    <view class="cover-actions" @click.stop>
                        <view class="action-btn" @click.stop="onChooseCover">更换</view>
                        <view class="action-btn danger" @click.stop="onRemoveCover">删除</view>
                    </view>
                </block>
            </view>

            <view class="title-box">
                <input class="title-input" v-model="title" type="text" placeholder="请填写标题">
            </view>

            <view class="activity-box">
                <view class="activity-item" @click="showActivityTypePicker">
                    <view class="item-left">
                        <image :src="IMAGE_URL + '/static/community/icon10.png'" style="width: 28rpx; height: 28rpx;"></image>
                        <text class="item-label">活动类型</text>
                    </view>
                    <view class="item-right">
                        <text class="item-value">{{ activityTypeOptions[activityType].text }}</text>
                        <u-icon name="arrow-right" color="#999" size="24rpx"></u-icon>
                    </view>
                </view>

                <view class="activity-item" @click="showActivityTimePicker">
                    <view class="item-left">
                        <image :src="IMAGE_URL + '/static/community/icon11.png'" style="width: 28rpx; height: 28rpx;"></image>
                        <text class="item-label">活动时间</text>
                    </view>
                    <view class="item-right">
                        <text class="item-value">{{ activityTimeText }}</text>
                        <u-icon name="arrow-right" color="#999" size="24rpx"></u-icon>
                    </view>
                </view>

                <view class="activity-item" @click="showRegistrationTimePicker">
                    <view class="item-left">
                        <image :src="IMAGE_URL + '/static/community/icon11.png'" style="width: 28rpx; height: 28rpx;"></image>
                        <text class="item-label">报名时间</text>
                    </view>
                    <view class="item-right">
                        <text class="item-value">{{ registrationTimeText }}</text>
                        <u-icon name="arrow-right" color="#999" size="24rpx"></u-icon>
                    </view>
                </view>

                <view class="activity-item" @click="goToAddressSelect">
                    <view class="item-left">
                        <image :src="IMAGE_URL + '/static/community/icon12.png'" style="width: 28rpx; height: 28rpx;"></image>
                        <text class="item-label">活动地址</text>
                    </view>
                    <view class="item-right">
                        <text class="item-value">{{ activityAddress }}</text>
                        <u-icon name="arrow-right" color="#999" size="24rpx"></u-icon>
                    </view>
                </view>
            </view>

            <!-- 活动类型选择器 -->
            <u-picker
                :show="showActivityType"
                :columns="[Object.values(activityTypeOptions)]"
                @confirm="onActivityTypeConfirm"
                @cancel="showActivityType = false"
            ></u-picker>

                         <!-- 活动时间选择器 -->
             <u-datetime-picker
                 :title="activityTimePickerType === 'start' ? '选择开始时间' : '选择结束时间'"
                 :show="showActivityTime"
                 mode="datetime"
                 :min-date="activityTimePickerType === 'start' ? activityTimeMinDate : activityEndTimeMinDate"
                 @confirm="onActivityTimeConfirm"
                 @cancel="showActivityTime = false"
             ></u-datetime-picker>

                         <!-- 报名时间选择器 -->
             <u-datetime-picker
                 :title="registrationTimePickerType === 'start' ? '选择开始时间' : '选择结束时间'"
                 :show="showRegistrationTime"
                 mode="datetime"
                 :min-date="registrationTimePickerType === 'start' ? registrationTimeMinDate : registrationEndTimeMinDate"
                 @confirm="onRegistrationTimeConfirm"
                 @cancel="showRegistrationTime = false"
             ></u-datetime-picker>

            <view class="content-box-item">
                <view class="content-title">内容</view>
                <view class="content-item">
                    <sp-editor
                        class="editor"
                        :toolbar-config="{
                            excludeKeys:['export','image','video','link','direction'],
                            iconSize: '18px',
                        }"
                        placeholder="请输入内容..."
                        @input="onEditorChange"
                    ></sp-editor>
                </view>
            </view>
        </view>
        <footer-vue>
            <view class="confirm-btn" @click="handlePublish">确认发布</view>
        </footer-vue>
    </view>
</template>
<script>
import headerVue from '@/components/header.vue';
import footerVue from '@/components/fixed-footer/index.vue';
import { postCommunityactivityPublish, postUploadNow } from '@/api/index.js';
export default {
    name: 'real-time-info',
    components: {
        headerVue,
        footerVue
    },
    data() {
        return {
            title: '',
            contentHtml: '',
            coverUrl: '',
            // 活动类型相关
            activityType: 1,
            activityTypeOptions: {"1":{text: '社区活动', value: 1}, "2":{text: '热门活动', value: 2}, "3":{text: '邻里互动', value: 3}},
            showActivityType: false,
            // 活动时间相关
            activityStartTime: '',
            activityEndTime: '',
            showActivityTime: false,
            activityTimePickerType: 'start', // 'start' 或 'end'
            // 报名时间相关
            registrationStartTime: '',
            registrationEndTime: '',
            showRegistrationTime: false,
            registrationTimePickerType: 'start', // 'start' 或 'end'
            // 活动地址
            activityAddress: '请选择',
            selectedAddress: null
        }
    },
    computed: {
        activityTimeText() {
            if (!this.activityStartTime && !this.activityEndTime) {
                return '请选择'
            }
            if (this.activityStartTime && this.activityEndTime) {
                return `${this.activityStartTime} ~ ${this.activityEndTime}`
            }
            return this.activityStartTime || this.activityEndTime
        },
        registrationTimeText() {
            if (!this.registrationStartTime && !this.registrationEndTime) {
                return '请选择'
            }
            if (this.registrationStartTime && this.registrationEndTime) {
                return `${this.registrationStartTime} ~ ${this.registrationEndTime}`
            }
            return this.registrationStartTime || this.registrationEndTime
        },
        activityTimeMinDate() {
            const today = new Date()
            today.setHours(0, 0, 0, 0)
            return today.getTime()
        },
                 registrationTimeMinDate() {
             const today = new Date()
             today.setHours(0, 0, 0, 0)
             return today.getTime()
         },
         activityEndTimeMinDate() {
             if (!this.activityStartTime) {
                 return this.activityTimeMinDate
             }
             // 将开始时间转换为时间戳，作为结束时间的最小值（至少间隔1小时）
             const startDate = new Date(`2024/${this.activityStartTime}`)
             const minEndDate = new Date(startDate.getTime() + 60 * 60 * 1000) // 加1小时
             return minEndDate.getTime()
         },
         registrationEndTimeMinDate() {
             if (!this.registrationStartTime) {
                 return this.registrationTimeMinDate
             }
             // 将开始时间转换为时间戳，作为结束时间的最小值（至少间隔1小时）
             const startDate = new Date(`2024/${this.registrationStartTime}`)
             const minEndDate = new Date(startDate.getTime() + 60 * 60 * 1000) // 加1小时
             return minEndDate.getTime()
         }
    },
    methods: {
        onEditorChange(val) {
            this.contentHtml = val.html
        },
        async onChooseCover() {
            try {
                const res = await uni.chooseImage({
                    count: 1,
                    sizeType: ['compressed'],
                    sourceType: ['album','camera']
                })
                if (res && res.tempFilePaths && res.tempFilePaths.length) {
                    this.coverUrl = res.tempFilePaths[0]
                }
            } catch (e) {}
        },
        onRemoveCover() {
            this.coverUrl = ''
        },
        onPreviewCover() {
            if (!this.coverUrl) return
            uni.previewImage({ current: this.coverUrl, urls: [this.coverUrl] })
        },
        // 活动类型选择器
        showActivityTypePicker() {
            this.showActivityType = true
        },
        onActivityTypeConfirm(e) {
            this.activityType = e.value[0].value
            this.showActivityType = false
        },

        // 活动时间选择器
        showActivityTimePicker() {
            this.activityTimePickerType = 'start'
            this.showActivityTime = true
        },
        onActivityTimeConfirm(e) {
            const timestamp = e.value
            const date = new Date(timestamp)
            const formattedDate = this.formatDateTime(date)
            
                         if (this.activityTimePickerType === 'start') {
                 this.activityStartTime = formattedDate
                 // 如果结束时间早于开始时间或间隔不足1小时，清空结束时间
                 if (this.activityEndTime && this.compareTime(this.activityEndTime, formattedDate) <= 60 * 60 * 1000) {
                     this.activityEndTime = ''
                 }
                 // 自动切换到结束时间选择
                 this.activityTimePickerType = 'end'
                 this.showActivityTime = true
             } else {
                 this.activityEndTime = formattedDate
                 this.showActivityTime = false
             }
        },

        // 报名时间选择器
        showRegistrationTimePicker() {
            this.registrationTimePickerType = 'start'
            this.showRegistrationTime = true
        },
        onRegistrationTimeConfirm(e) {
            const timestamp = e.value
            const date = new Date(timestamp)
            const formattedDate = this.formatDateTime(date)
            
                         if (this.registrationTimePickerType === 'start') {
                 this.registrationStartTime = formattedDate
                 // 如果结束时间早于开始时间或间隔不足1小时，清空结束时间
                 if (this.registrationEndTime && this.compareTime(this.registrationEndTime, formattedDate) <= 60 * 60 * 1000) {
                     this.registrationEndTime = ''
                 }
                 // 自动切换到结束时间选择
                 this.registrationTimePickerType = 'end'
                 this.showRegistrationTime = true
             } else {
                 this.registrationEndTime = formattedDate
                 this.showRegistrationTime = false
             }
        },

                 // 地址选择
         goToAddressSelect() {
             uni.navigateTo({
                 url: '/views/address/manage?isClick=true',
             })
         },
         
         // 页面显示时检查store中的地址选择
         onShow() {
             this.checkSelectedAddress()
         },
         
         // 检查store中的地址选择
         checkSelectedAddress() {
             const selectedAddress = this.$store.state.selectedAddress
             if (selectedAddress) {
                 this.selectedAddress = selectedAddress
                 this.activityAddress = selectedAddress.address_detail
                 // 清除store中的选择，避免影响其他页面
                 this.$store.commit('SET_SELECTED_ADDRESS', null)
             }
         },

        // 工具方法
        formatDateTime(date) {
            const month = (date.getMonth() + 1).toString().padStart(2, '0')
            const day = date.getDate().toString().padStart(2, '0')
            const hours = date.getHours().toString().padStart(2, '0')
            const minutes = date.getMinutes().toString().padStart(2, '0')
            return `${month}/${day} ${hours}:${minutes}`
        },
        compareTime(time1, time2) {
            const date1 = new Date(`2024/${time1}`)
            const date2 = new Date(`2024/${time2}`)
            return date1.getTime() - date2.getTime()
        },

        async handlePublish() {
            if (!this.title.trim()) {
                uni.showToast({ title: '请填写标题', icon: 'none' })
                return
            }
            const pureText = this.contentHtml.replace(/<[^>]*>/g, '').trim()
            if (!pureText) {
                uni.showToast({ title: '请填写内容', icon: 'none' })
                return
            }
            if (!this.activityStartTime || !this.activityEndTime) {
                uni.showToast({ title: '请选择活动时间', icon: 'none' })
                return
            }
            if (!this.registrationStartTime || !this.registrationEndTime) {
                uni.showToast({ title: '请选择报名时间', icon: 'none' })
                return
            }
            if (this.activityAddress === '请选择') {
                uni.showToast({ title: '请选择活动地址', icon: 'none' })
                return
            }
            uni.showLoading({ title: '发布中...' })
            const res = await postUploadNow(this.coverUrl)
            const data = JSON.parse(res.data)
            this.coverUrl = data.url
            const payload = {
                title: this.title.trim(),
                content: this.contentHtml,
                image_urls: this.coverUrl,
                category_id: this.activityType,
                activity_start_time: this.activityStartTime,
                activity_end_time: this.activityEndTime,
                register_start_time: this.registrationStartTime,
                register_end_time: this.registrationEndTime,
                address: (this.selectedAddress.address_detail + this.selectedAddress.address) || (this.activityAddress.address_detail + this.activityAddress.address)
            }
            // TODO: 调用发布接口
            const res2 = await postCommunityactivityPublish(payload)
            uni.hideLoading()
            if (res2.errno == 0) { 
                uni.showToast({ title: '发布成功', icon: 'success' })
                this.resetForm()
                uni.navigateBack()
            } else {
                uni.showToast({ title: res2.msg || '发布失败！' })
            }
        },
        resetForm() {
            this.title = ''
            this.contentHtml = ''
            this.coverUrl = ''
            this.activityType = 1
            this.activityStartTime = ''
            this.activityEndTime = ''
            this.registrationStartTime = ''
            this.registrationEndTime = ''
            this.activityAddress = '请选择'
            this.selectedAddress = null
        }
    }
}
</script>
<style lang="scss" scoped>
.real-time-info-container {
    width: 100%;
    min-height: 100vh;
    background: linear-gradient( 180deg, #e6f0ff 0%, #feffff 100%);
}
.nav-item-title {
    display: flex;
    align-items: center;
    justify-content: center;
}
.nav-item-title text {
    font-size: 28rpx;
    color: #999999;
    font-weight: 500;
    margin-left: 5rpx;
}

.title-box {
    width: 100%;
    height: 94rpx;
    margin-top: 28rpx;
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: center;
}
.title-input {
    width: 100%;
    height: 100%;
    padding: 0 30rpx;
    background: #FFFFFF;
    box-shadow: 0rpx 0rpx 16rpx 0rpx rgba(0,0,0,0.04);
    border-radius: 12rpx 12rpx 12rpx 12rpx;
    font-size: 28rpx;
    color: #333333;
}
.title-input::placeholder {
    font-size: 28rpx;
    color: #999999;
}
.content-box {
    width: 100%;
    padding: 0 32rpx 180rpx;
    margin-top: 28rpx;
    box-sizing: border-box;
}
.cover-img {
    width: 100%;
    height: 300rpx;
    background: #FFFFFF;
    box-shadow: 0 0 16rpx rgba(0,0,0,0.04);
    border-radius: 12rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;
    position: relative;
}
.cover-placeholder {
    display: flex;
    flex-direction: column;
    align-items: center;
    color: #bbb;
}
.cover-tip {
    margin-top: 12rpx;
    font-size: 26rpx;
    color: #999;
}
.cover-image {
    width: 100%;
    height: 100%;
}
.cover-actions {
    position: absolute;
    right: 16rpx;
    bottom: 16rpx;
    display: flex;
    gap: 12rpx;
}
.action-btn {
    padding: 8rpx 16rpx;
    background: rgba(0,0,0,0.55);
    color: #fff;
    border-radius: 24rpx;
    font-size: 24rpx;
}
.action-btn.danger {
    background: rgba(252,70,70,0.85);
}
.activity-box {
    margin-top: 28rpx;
    background: #FFF;
    padding: 0 28rpx;
    box-shadow: 0rpx 0rpx 16rpx 0rpx rgba(0,0,0,0.04);
    border-radius: 12rpx;
}

.activity-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 32rpx 0;
    border-bottom: 1rpx solid #f5f5f5;
}

.activity-item:last-child {
    border-bottom: none;
}

.item-left {
    display: flex;
    align-items: center;
}

.item-label {
    margin-left: 16rpx;
    font-size: 28rpx;
    color: #333;
    font-weight: 500;
}

.item-right {
    display: flex;
    align-items: center;
    justify-content: flex-end;
    flex: 1;
    margin-left: 10rpx;
}

.item-value {
    margin-right: 12rpx;
    font-size: 28rpx;
    color: #666;
}

.content-box-item {
    height: 100%;
    margin-top: 28rpx;
    background: #FFF;
    padding: 28rpx;
    box-shadow: 0rpx 0rpx 16rpx 0rpx rgba(0,0,0,0.04);
    border-radius: 12rpx 12rpx 12rpx 12rpx;
}
.content-title {
    font-size: 28rpx;
    font-weight: bold;
}
.content-item {
    width: 100%;
    height: 100%;
}
.editor {
    width: 100%;
    margin-top: 20rpx;
    height: 1000rpx;

}
.confirm-btn {
    width: 100%;
    height: 76rpx;
    background: linear-gradient( 90deg, #0785CF 0%, #25A4EF 100%);
    box-shadow: 0rpx 4rpx 20rpx 0rpx rgba(7,133,207,0.1);
    border-radius: 60rpx 60rpx 60rpx 60rpx;
    font-weight: 500;
    font-size: 36rpx;
    color: #FFFFFF;
    text-align: center;
    line-height: 76rpx;
}
</style>